<template >
  <div class="updataArticle">
    <!-- 编辑面板 -->
    <el-dialog :fullscreen="true" :visible.sync="dialogVisible" :close="dialogVisible_item_close">
      <h2>文章详情--ID：{{ shs_articleid }}</h2>

      <el-form class="form1" :label-position="labelPosition" label-width="80px" :model="form_item" :rules="rules1"
        ref="form_item">
        <el-form-item label="封面">
          <el-upload action="none" list-type="picture-card" :on-remove="handleRemove" :on-change="check_file"
            :auto-upload="false" :drag="false" :multiple="false" :show-file-list="false">
            <img v-if="uploadURL" :src="uploadURL" style="width: 100%" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <el-dialog :visible.sync="dialogVisible_item2">
              <img width="100%" height="100%" :src="image_item2" alt="加载失败" />
            </el-dialog>
          </el-upload>
        </el-form-item>
        <el-form-item class="confim_isok">
          <el-button @click="dialogVisible_item_close">取 消</el-button>
          <el-button type="primary" @click="submit_updata('form_item')">更 新</el-button>
        </el-form-item>
        <el-form-item label="分类名称" style="width: 50%" prop="classID">
          <el-select v-model="classID" placeholder="请选择">
            <el-option v-for="item in classList" :key="item.classID" :label="item.className" :value="item.classID"
              :disabled="item.active == 0">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" style="width: 50%">
          <template>
            <el-select v-model="check_tagitem" multiple placeholder="请选择">
              <el-option v-for="item in tag_items" :key="item.tagID" :label="item.tagName" :value="item.tagID"
                :disabled="item.active == 0">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="标题" prop="title" style="width: 50%">
          <el-input v-model="form_item.title"></el-input>
        </el-form-item>
        <el-form-item label="摘要" style="width: 50%">
          <el-input v-model="form_item.summary"></el-input>
        </el-form-item>

        <el-form-item label="点赞数" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.likeCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="踩/个" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.unlikeCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="浏览量" style="width: 50%">
          <template>
            <el-input-number v-model="form_item.viewCount" controls-position="right" :min="0" :max="99999999">
            </el-input-number>
          </template>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker readonly disabled :value="createtime" type="datetime" size="small" placeholder="选择日期时间"
            placement="bottom-start">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker readonly disabled :value="updatetime" type="datetime" size="small" placeholder="选择日期时间"
            placement="bottom-start">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- <el-input v-model="form_item.content"></el-input> -->
          <template>
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: 500px; overflow-y: hidden" v-model="form_item.content"
                :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
            </div>
          </template>
        </el-form-item>
      </el-form>
      <!-- {{ form_item.content }} -->
      <!-- check_tagitem： {{ check_tagitem }} -->
    </el-dialog>
  </div>
</template>

<script>
/**导入element ui 加载 */
import { Loading } from "element-ui";
/*导入更新 获取 文章 */
import { updataArticle } from "@/request/api";
/*导入上传图片 */
import { upload_img } from "@/request/api";
/*导入添加*/
// import {insertArticle} from "@/request/api";
/*导入文章id获取文章 */
import { getArticle_id } from "@/request/api";
/*导入获取标签 */
import { getTags } from "@/request/api";
/*导入获取分类 */
import { getclass_listV2 } from "@/request/api";
/*导入 富文本编辑器-wangeditor */
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
/**导入样式 */
import "@wangeditor/editor/dist/css/style.css";
export default {
  name: "shsCeshi",
  props: {
    articleID: {
      type: Number,
      default: 0,
    },
    dialogVisible_item: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      /*富文本编辑器*/
      editor: null,
      html: "<p>hello</p>",
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple'

      timer: null, //计数器
      labelPosition: "right", //右对齐
      shs_articleid: null, //文章id
      form_item: { title: null }, //文章数据
      dialogVisible: this.dialogVisible_item, //对话框显隐
      tag_items: {}, //标签列表
      classList: {}, //分类列表
      check_tagitem: [], //选中的标签
      classID: 0, //选中的分类id
      dialogVisible_item2: false, //预览图 显示隐藏 标识
      image_item2: null, //预览图url
      uploadURL: "", //上传图片的URL
      currentFile: null, //最新图片实例
      rules1: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" },
          { min: 5, message: "长度应大于5个字符", trigger: "blur" },
        ],
      },
    };
  },

  /**挂载之后 */
  mounted() {
    console.log("挂载之后", this.articleID);
    this.shs_articleid = this.articleID;
    this.init();
  },
  beforeDestroy() {
    // console.log("销毁之前");
    this.shs_articleid = null;
    // clearInterval(this.timer);
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
  destroyed() {
    // console.log("销毁后", this.shs_articleid);
  },
  methods: {
    /**富文本编辑器 创建后 */
    onCreated(editor) {
      editor.getMenuConfig('uploadImage').server = "/api/upload_file_imageV2";//上传图片

      editor.getMenuConfig('uploadVideo').server = "/api/upload_videoV2";//上传视频
      editor.getMenuConfig('uploadVideo').fieldName = "wangeditor-uploaded-video";//视频文件名称
      editor.getMenuConfig('uploadVideo').headers = { 'authorization': localStorage.getItem("usertoken") }
      // 单个文件的最大体积限制，默认为 10M
      editor.getMenuConfig('uploadVideo').maxFileSize = 5 * 1024 * 1024, // 5M
        editor.getMenuConfig('uploadImage').headers = { 'authorization': localStorage.getItem("usertoken") }
      // editor.getMenuConfig('uploadImage') // 获取 uploadImage 的当前配置
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    init() {
      let _this = this;
      let loadingInstance = null;
      if (this.articleID) {
        loadingInstance = Loading.service({
          text: "加载中...",
          background: "rgba(0, 0, 0, 0.7)",
        });
      }
      this.shs_articleid = this.articleID;
      if (this.articleID) {
        getclass_listV2({ begin_index: 0, page_size: 99999 })
          .then((data) => {
            if (data.data.code == 200) {
              this.classList = data.data.data.list;
              return getTags({ begin_index: 0, page_size: 99999 });
            }
          })
          .then((data) => {
            if (data.data.code == 200) {
              this.tag_items = data.data.data.list;
              return getArticle_id({ articleID: this.shs_articleid });
            }
          })
          .then((data) => {
            if (data.data.code == 200) {
              this.form_item = data.data.data[0];
              let tag_list_id = data.data.data[0].tag_list_id;
              console.log("标签", tag_list_id);//789
              this.check_tagitem = [];
              for (let i = 0; i < tag_list_id.length; i++) {
                if (tag_list_id[i]) {
                  this.check_tagitem[i] = parseInt(tag_list_id[i]);
                }
              }
              this.classID = data.data.data[0].classID; //给分类id赋值
              //给封面赋值
              this.uploadURL = data.data.data[0].cover;
              // loadingInstance.close();
              _this.$nextTick(() => {
                // 以服务的方式调用的 Loading 需要异步关闭
                loadingInstance.close();
              });
              _this.dialogVisible = true; //显隐对话框
            }
          });
      }
    },
    //更新数据
    update() {
      let obj = {
        articleID: this.shs_articleid, //文章id
        cover: this.form_item.cover, //封面
        title: this.form_item.title, //标题
        summary: this.form_item.summary, //摘要
        content: this.form_item.content, //内容
        likeCount: this.form_item.likeCount, //点赞
        unlikeCount: this.form_item.unlikeCount, //踩
        viewCount: this.form_item.viewCount, //浏览量
        relation_id: this.form_item.relation_id, //关联id
        classID: this.classID, //分类
        tag_list_id: this.check_tagitem, //标签
        active: this.form_item.active, //是否启用
        updatetime: new Date(), //更新时间
      };
      if (!this.currentFile && obj.cover.length < 1) {
        this.$message({ message: "请选择封面", type: "info" });
        return;
      }
      /*上传图片--封面 */
      let formdata = new FormData();
      if (this.currentFile) {
        //需要上传封面
        //保存formdata
        formdata.append("single_image_file", this.currentFile.raw);
        upload_img(formdata)
          .then((data) => {
            if (data.data.code == 1) {
              obj.cover = data.data.path; //图片网址
              return updataArticle(obj);
            } else {
              /*封面上传失败*/
              this.$notify.error({
                message: data.data.msg,
              });
            }
          })
          .then((data) => {
            if (data.data.code == 200) {
              this.$notify({
                title: "Hint",
                message: data.data.msg,
                type: "success",
              });
              this.dialogVisible = false;
              this.$emit("list_change", true);
            } else {
              this.$message({ message: data.data.msg, type: "error" });
            }
          })
          .catch((err) => {
            this.$message({ message: err, type: "error" });
          });
      } else {
        //不需要上传封面--封面没有改变
        updataArticle(obj)
          .then((data) => {
            if (data.data.code == 200) {
              this.$notify({
                title: "Hint",
                message: data.data.msg,
                type: "success",
              });
              this.dialogVisible = false;
              this.$emit("list_change", true);
            } else {
              this.$message({ message: data.data.msg, type: "error" });
            }
          })
          .catch((err) => {
            this.$message({ message: err, type: "error" });
          });
      }
    },
    dialogVisible_item_close() {
      this.dialogVisible = false;
    },
    //提交按钮 更新数据
    submit_updata(form_item) {
      let _this = this;
      _this.$refs[form_item].validate((vali) => {
        if (vali) {
          _this
            .$confirm("你确定要修改当前的数据吗")
            .then(() => {
              //调用修改的函数
              _this.update();
            })
            .catch(() => { });
        }
      });
    },
    // 预览图
    handlePictureCardPreview(file) {
      this.dialogVisible_item2 = true;
      this.image_item2 = URL.createObjectURL(file.raw);
    },
    // 图片移除 清空当前图片实例
    handleRemove() {
      this.currentFile = null;
      // console.log("file", file, "filelist", fileList);
    },
    //图片选择后
    check_file(file) {
      this.currentFile = file; // 赋值到最新图片实例
      this.uploadURL = URL.createObjectURL(file.raw); //创建对象的URL
      this.form_item.cover = URL.createObjectURL(file.raw);
    },
  },
  watch: {
    articleID(val) {
      this.shs_articleid = val;
    },
    dialogVisible(val) {
      this.$emit("dialogVisible_item_change", val);
    },
  },
  computed: {
    createtime() {
      //创建时间赋值
      return this.form_item.createAt || "2022-10-01 00:00:00";
    },
    updatetime() {
      //更新时间赋值
      return this.form_item.updatetime || "2022-10-01 00:00:00";
    },
  },
  components: {
    Editor,
    Toolbar,
  },

};
</script>

<style scoped>
.form1 {
  margin: 20px 0;
}

.confim_isok {
  position: absolute;
  right: 30px;
}
</style>
